# app.py
from flask import Flask, render_template, request, redirect, url_for, flash, session
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from models import db, User, Product, Order, OrderItem
from database import init_db
import os

app = Flask(__name__)
app.secret_key = 'your-secret-key-here'

# 初始化数据库
init_db(app)

# 初始化登录管理
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# ========== 路由 ==========
@app.route('/')
def index():
    products = Product.query.all()
    return render_template('index.html', products=products)

@app.route('/product/<int:product_id>')
def product_detail(product_id):
    product = Product.query.get_or_404(product_id)
    return render_template('product.html', product=product)

# ✅ 加入购物车（检查库存）
@app.route('/add_to_cart/<int:product_id>')
def add_to_cart(product_id):
    product = Product.query.get_or_404(product_id)
    
    # 检查库存
    if product.stock <= 0:
        flash(f'❌ {product.name} 已售罄！', 'error')
        return redirect(url_for('index'))
    
    if 'cart' not in session:
        session['cart'] = {}
    cart = session['cart']
    pid = str(product_id)
    
    # 检查加入后是否超库存
    current_qty = cart.get(pid, 0)
    if current_qty + 1 > product.stock:
        flash(f'❌ {product.name} 库存不足！最多可购买 {product.stock} 件', 'error')
        return redirect(url_for('index'))
    
    cart[pid] = current_qty + 1
    session['cart'] = cart
    flash(f'✅ {product.name} 已加入购物车', 'success')
    return redirect(url_for('index'))

@app.route('/cart')
def view_cart():
    cart = session.get('cart', {})
    cart_items = []
    total = 0
    for pid, qty in cart.items():
        product = Product.query.get(int(pid))
        if product:
            item_total = product.price * qty
            cart_items.append({
                'product': product,
                'quantity': qty,
                'item_total': item_total
            })
            total += item_total
    return render_template('cart.html', cart_items=cart_items, total=total)

@app.route('/remove_from_cart/<int:product_id>')
def remove_from_cart(product_id):
    cart = session.get('cart', {})
    pid = str(product_id)
    if pid in cart:
        del cart[pid]
        session['cart'] = cart
        flash('🗑️ 商品已移除')
    return redirect(url_for('view_cart'))

# ✅ 下单（扣减库存）
@app.route('/checkout', methods=['POST'])
@login_required
def checkout():
    cart = session.get('cart', {})
    if not cart:
        flash('🛒 购物车为空')
        return redirect(url_for('view_cart'))

    try:
        # 创建订单
        total = 0
        order = Order(user_id=current_user.id, total_amount=0)
        db.session.add(order)
        db.session.flush()

        # 检查库存 & 创建订单项
        for pid, qty in cart.items():
            product = Product.query.get(int(pid))
            if not product:
                raise Exception("商品不存在")
            
            # 再次检查库存（防止并发超卖）
            if product.stock < qty:
                raise Exception(f"{product.name} 库存不足！")

            # 扣减库存（关键！）
            product.stock -= qty

            # 创建订单项
            item_total = product.price * qty
            total += item_total
            order_item = OrderItem(
                order_id=order.id,
                product_id=product.id,
                quantity=qty,
                price=product.price
            )
            db.session.add(order_item)

        order.total_amount = total
        db.session.commit()  # ✅ 事务提交，库存和订单同时生效

        session.pop('cart', None)
        flash(f'🎉 订单 #{order.id} 提交成功！感谢购买！', 'success')
        return redirect(url_for('orders'))

    except Exception as e:
        db.session.rollback()  # ❌ 出错回滚
        flash(f'❌ 下单失败：{str(e)}', 'error')
        return redirect(url_for('view_cart'))

@app.route('/orders')
@login_required
def orders():
    user_orders = Order.query.filter_by(user_id=current_user.id).order_by(Order.created_at.desc()).all()
    return render_template('orders.html', orders=user_orders)

# ========== 用户系统（简化版） ==========
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if User.query.filter_by(username=username).first():
            flash('❌ 用户名已存在')
        else:
            hashed_pw = generate_password_hash(password)
            new_user = User(username=username, password=hashed_pw)
            db.session.add(new_user)
            db.session.commit()
            flash('✅ 注册成功，请登录')
            return redirect(url_for('login'))
    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password, password):
            login_user(user)
            flash('✅ 登录成功')
            return redirect(url_for('index'))
        else:
            flash('❌ 用户名或密码错误')
    return render_template('login.html')

@app.route('/logout')
def logout():
    logout_user()
    session.pop('cart', None)
    flash('👋 已登出')
    return redirect(url_for('index'))

if __name__ == '__main__':
    os.makedirs('instance', exist_ok=True)
    os.makedirs('static/uploads', exist_ok=True)
    app.run(debug=True, host='0.0.0.0', port=5000)